package com.ch.android.networklib

import android.content.Context
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 * Author: conghao
 * Date: 2023/12/26 11:31
 * Description: RequestClient
 */
class RequestClient private constructor() {
    companion object {
        private lateinit var appContext: Context
        @Volatile private var instance: RequestClient? = null
        private fun getInstance(context: Context): RequestClient {
            if (instance == null) {
                synchronized(RequestClient::class) {
                    if (instance == null) {
                        // 避免直接使用构造方法的参数context，因为这样会持有activity的引用，容易造成内存泄漏
                        appContext = context
                        instance = RequestClient()
                    }
                }
            }
            return instance!!
        }

        private val defaultClient: OkHttpClient by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(MyInterceptor(appContext))
                .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
                .build()
        }

        private val defaultRetrofit: Retrofit by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            Retrofit.Builder()
                .baseUrl(ApiService.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .client(defaultClient)
                .build()
        }
        private val apiService: ApiService by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            defaultRetrofit.create(ApiService::class.java)
        }

        fun getApiService(context: Context): ApiService {
            getInstance(context)
            return apiService
        }
    }

}
